package com.samphanie.security.config;

import com.samphanie.common.service.IRedisService;
import com.samphanie.security.security.handler.CustomClientAuthenticationEntryPoint;
import com.samphanie.security.security.handler.RestAuthenticationEntryPoint;
import com.samphanie.security.security.oauth.filter.CustomClientCredentialsTokenEndpointFilter;
import com.samphanie.security.security.oauth.granter.CaptchaTokenGranter;
import com.samphanie.security.security.oauth.granter.SmsCodeTokenGranter;
import com.samphanie.security.security.oauth.granter.SocialTokenGranter;
import com.samphanie.security.security.properties.AuthConstants;
import com.samphanie.security.security.properties.AuthProperties;
import com.samphanie.security.security.service.impl.ClientDetailsServiceImpl;
import com.samphanie.security.security.service.impl.SingleLoginTokenService;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 认证服务器配置
 *
 * @author Dries
 * @email 1451691457@qq.com
 */
@Configuration
@EnableAuthorizationServer
@RequiredArgsConstructor
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

    private final RestAuthenticationEntryPoint authenticationEntryPoint;
    private final CustomClientAuthenticationEntryPoint customClientAuthenticationEntryPoint;
    private final ClientDetailsServiceImpl clientService;
    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final KeyPair keyPair;
    private final TokenEnhancer jwtTokenEnhancer;
    private final IRedisService redisService;
    private final AuthRequestFactory factory;
    private final RedisConnectionFactory redisConnectionFactory;
    private final AuthProperties authProperties;
    @Resource
    private AuthorizationServerEndpointsConfiguration configuration;

    /**
     * 配置 Jdbc 版本的 JdbcClientDetailsService
     *
     * @param clients 客户端
     * @throws Exception 异常
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clientService.setSelectClientDetailsSql(AuthConstants.SELECT_CLIENT_DETAIL_SQL);
        clientService.setFindClientDetailsSql(AuthConstants.FIND_CLIENT_DETAIL_SQL);
        // clientService.setPasswordEncoder(passwordEncoder);
        clients.withClientDetails(clientService);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair);
        return converter;
    }

    /**
     * 配置授权服务器的 token 接入点
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        String path = "/oauth/token";
        try {
            // 获取自定义映射路径，比如 ((AuthorizationServerEndpointsConfigurer) endpoints).pathMapping("/oauth/token", "/my/token");
            path = configuration.oauth2EndpointHandlerMapping().getServletPath(path);
        } catch (Exception ignored) {
        }
        CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security, path);
        endpointFilter.afterPropertiesSet();
        // 自定义错误格式
        endpointFilter.setAuthenticationEntryPoint(customClientAuthenticationEntryPoint);
        security.addTokenEndpointAuthenticationFilter(endpointFilter);

        /*
        * allowFormAuthenticationForClients的作用是让/oauth/token支持client_id以及client_secret作登录认证。
        * oauthServerSecurity.allowFormAuthenticationForClients()即设置allowFormAuthenticationForClients = true;
        * 作用是在BasicAuthenticationFilter之前添加ClientCredentialsTokenEndpointFilter，使用ClientDetailUserDeailsService来进行client端登录的验证。
        * 同时，使用allowFormAuthenticationForClients()和我们自定义的CustomClientCredentialsTokenEndpointFilter，
        * 会导致oauth2仍然使用allowFormAuthenticationForClients中默认的ClientCredentialsTokenEndpointFilter进行过滤，
        * 致使我们的自定义CustomClientCredentialsTokenEndpointFilter不生效。
        * 因此，在使用CustomClientCredentialsTokenEndpointFilter时，不再需要开启allowFormAuthenticationForClients()功能。
        * */
        security
                .authenticationEntryPoint(authenticationEntryPoint)
                // 允许表单认证请求
                // .allowFormAuthenticationForClients()
                // spel表达式 访问公钥端点（/auth/token_key）需要认证
                .tokenKeyAccess("isAuthenticated()")
                // spel表达式 访问令牌解析端点（/auth/check_token）需要认证
                .checkTokenAccess("permitAll()");
    }

    /**
     * 配置授权访问的接入点
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        DefaultTokenServices tokenServices = createDefaultTokenServices();
        // token增强链
        TokenEnhancerChain chain = new TokenEnhancerChain();
        // 把jwt增强，与额外信息增强加入到增强链
        List<TokenEnhancer> enhancers = new ArrayList<>();
        enhancers.add(jwtTokenEnhancer);
        enhancers.add(jwtAccessTokenConverter());
        chain.setTokenEnhancers(enhancers);
        tokenServices.setTokenEnhancer(chain);
        // 配置tokenServices参数
        addUserDetailsService(tokenServices);
        endpoints
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenGranter(tokenGranter(endpoints, tokenServices))
                .tokenStore(tokenStore()) // 从 token 中读取特定字段构成 Authentication
                .tokenServices(tokenServices)
                .accessTokenConverter(jwtAccessTokenConverter());
    }

    /**
     * 重点
     * 先获取已经有的五种授权，然后添加我们自己的进去
     *
     * @param endpoints AuthorizationServerEndpointsConfigurer
     * @return TokenGranter
     */
    public TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints, AuthorizationServerTokenServices tokenServices) {
        List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));

        // 短信验证码模式
        granters.add(new SmsCodeTokenGranter(authenticationManager, tokenServices, endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(), redisService));
        // 验证码模式
        granters.add(new CaptchaTokenGranter(authenticationManager, tokenServices, endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(), redisService));
        // 社交登录模式
        granters.add(new SocialTokenGranter(authenticationManager, tokenServices, endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(), redisService, factory));
        // 增加密码模式
        granters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices,
                endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
        return new CompositeTokenGranter(granters);

    }

    /**
     * 配置token存储到redis中
     */
    @Bean
    public RedisTokenStore redisTokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    private void addUserDetailsService(DefaultTokenServices tokenServices) {
        if (userDetailsService != null) {
            PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
            provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userDetailsService));
            tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
        }
    }

    /**
     * 创建默认的tokenServices
     *
     * @return DefaultTokenServices
     */
    private DefaultTokenServices createDefaultTokenServices() {
        DefaultTokenServices tokenServices = new SingleLoginTokenService(authProperties.isSingleSaveLogin());
        tokenServices.setTokenStore(redisTokenStore());
        // 支持刷新Token
        tokenServices.setSupportRefreshToken(Boolean.TRUE);
        tokenServices.setReuseRefreshToken(Boolean.FALSE);
        tokenServices.setClientDetailsService(clientService);
        addUserDetailsService(tokenServices);
        return tokenServices;
    }
}
